package com.jwater.core.manager.master;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jwater.core.common.InitLogger;
import com.jwater.core.common.JvmNames;
import com.jwater.core.manager.common.conf.CoreConfParse;
import com.jwater.core.metrics.JvmMetric;
import com.jwater.core.utils.ProcessUtils;
import com.jwater.launch.Jwater;

/**
 * @description: 管理进程入口类
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class MasterMain {
    protected static Logger logger = LoggerFactory.getLogger(MasterMain.class);

    /**
     * 强制kill之前的管理进程
     *
     * @param index
     */
    public static void killOld(int index) {
        int currId = JvmMetric.pid();
        logger.info("currId:" + currId);
        CoreConfParse conf = new CoreConfParse();
        conf.parse();
        List<Integer> ids = ProcessUtils.getProcessIds(Jwater.class.getName(),
                JvmNames.getMasterName(conf.getClusterName(), index));
        for (Integer id : ids) {
            if (id != currId) {
                try {
                    ProcessUtils.killById(id, true);
                } catch (Exception e) {
                    logger.error(e.toString(), e);
                }
            }
        }
    }

    public static void main(String[] args) {
        int id = Integer.parseInt(args[0]);
        InitLogger.initMaster(id);
        logger.info("master id:" + id);
        killOld(id);
        CoreConfParse coreConf = new CoreConfParse();
        coreConf.parse();
        MasterNode masterNode = new MasterNodeImpl(id, coreConf.getMembers(), coreConf);
        masterNode.start();
    }
}
